package com.traffic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.traffic.entity.Admin;
import com.traffic.entity.Resource;
import com.traffic.entity.User;
import com.traffic.mapper.ResourceMapper;
import com.traffic.service.AdminService;
import com.traffic.service.ResourceService;
import com.traffic.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/9/8
 */
@Service
// @CacheConfig(cacheNames = "resource")
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {
    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private ResourceMapper resourceMapper;

    // @CachePut(key = "#resource.id")
    @Override
    public Resource save(Resource resource, String account, Integer kind, Integer type) {
        if (kind == 0) {
            // 管理员上传图片资源
            Admin admin = adminService.get(account);
            resource.setKind(kind);
            resource.setType(type);
            resource.setCreateBy(admin.getId());
            resourceMapper.insert(resource);
        }else if (kind == 1) {
            // 用户上传图片资源
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("account", account);
            User user = userService.getOne(wrapper);
            resource.setKind(kind);
            resource.setType(type);
            resource.setCreateBy(user.getId());
            resourceMapper.insert(resource);
        }
        return resource;
    }

    // @Cacheable(value = "url", key = "#id")
    @Override
    public String getImgUrl(Long id) {
        return resourceMapper.selectById(id).getUrl();
    }

    // @CachePut(key = "#id")
    @Override
    public Resource get(Long id) {
        return resourceMapper.selectById(id);
    }

    // @CacheEvict(key = "#id")
    @Override
    public void delete(Long id) {
        resourceMapper.deleteById(id);
    }


    @Override
    public List<Resource> getCollectIcons() {

        QueryWrapper<Resource> wrapper = new QueryWrapper<>();

        return resourceMapper.selectList(wrapper.eq("type",3));
    }
}
